package dnl.dtools.grm.ssh.scrapers;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

public class ListScraper {

	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public SimpleFileInfo[] scrape(String lsOutput) {
		String[] lines = StringUtils.split(lsOutput, "\r\n");
		SimpleFileInfo[] infow = null;
		int mod = 0;
		if(lines[0].startsWith("total")){
			infow = new SimpleFileInfo[lines.length-1];
			mod = 1;
		}
		else {
			infow = new SimpleFileInfo[lines.length];
		}
		
		for (int i = mod; i < lines.length; i++) {
			String[] elements = splitLine(lines[i]);
			SimpleFileInfo inf = new SimpleFileInfo();
			infow[i-mod] = inf;
			
			inf.permissions = elements[0];
			inf.owner = elements[2];
			inf.group = elements[3];
			inf.size = Long.parseLong(elements[4]);
			try {
				inf.date = sdf.parse(elements[5]+" "+elements[6]).getTime();
			} catch (ParseException e) {
				e.printStackTrace();
			}
		
			inf.name = elements[8];
			if(inf.name.endsWith("/")){
				inf.directory = true;
			}

			if(inf.name.endsWith("/") || inf.name.endsWith("*")){
				inf.name = inf.name.substring(0, inf.name.length()-1);
			}
		}
		return infow;
	}
	
	private static String[] splitLine(String line){
		String[] segments = new String[9];
		int fromInd = 0;
		
		for (int i = 0; i < 9; i++) {
			int ind = line.indexOf(' ', fromInd);
			if(ind == fromInd){
				i--;
				fromInd++;
				continue;
			}
			if(i == 8){
				segments[i] = line.substring(fromInd, line.length());
			}
			else {
				segments[i] = line.substring(fromInd, ind);
			}
			fromInd = ind+1;
		}
		return segments;
	}

	public static class SimpleFileInfo {
		private String name;

		private String permissions;

		private String owner;

		private String group;

		private long date;

		private long size;
		
		private boolean directory;

		public boolean isDirectory() {
			return directory;
		}

		public long getSize() {
			return size;
		}

		public long getDate() {
			return date;
		}

		public String getGroup() {
			return group;
		}

		public String getName() {
			return name;
		}

		public String getOwner() {
			return owner;
		}

		public String getPermissions() {
			return permissions;
		}

		@Override
		public String toString() {
			return permissions+" "+owner+" "+group+" "+size+" "+sdf.format(new Date(date))+" "+name;
		}
	}
}
